const fs = require("fs");
const path = require("path");
const log4js = require('log4js');
const Raven = require('raven');

function init(opt = { appName: 'node' }) {
    if(opt.sentry) {
        Raven.config(opt.sentry.key).install();
    }
    let logDir = opt.logDir || path.resolve('.logs');
    if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir);
    }

    log4js.configure({
        //控制台输出
        appenders: {
            console: { type: 'console' },
            file: {
                type: "dateFile",
                filename: path.join(logDir, `${opt.appName}-log.log`),
                pattern: "-yyyy-MM-dd",
                alwaysIncludePattern: false,
                maxLogSize: 1024 * 1024
                //            category: 'normal'
            },
            error: {
                type: "dateFile",
                filename: path.join(logDir, `${opt.appName}-error.log`),
                pattern: "-yyyy-MM-dd",
                alwaysIncludePattern: false,
                maxLogSize: 1024 * 1024
            }
        },
        categories: {
            default: { appenders: ['console', 'file'], level: 'info' },
            error: { appenders: ['error'], level: 'error' },
        }
    });

    console.log = function (...args) {
        let logger = log4js.getLogger('default');
        logger.log("info", ...args)
    }

    console.info = function (...args) {
        let logger = log4js.getLogger('default');
        logger.info(...args)
    }

    console.warn = function (...args) {
        let logger = log4js.getLogger('default');
        logger.warn(...args)
    }

    console.error = function (...args) {
        let logger = log4js.getLogger('error');
        logger.error(...args);
        if(opt.sentry) {
            if(args[0] instanceof Error) {
                Raven.captureException(args[0]);
            } else {
                Raven.captureException(new Error(args));
            }
        }        
    }
}

exports.getLogger = function (name) {
    var logger = log4js.getLogger(name);
    logger.level = 'INFO';
    return logger;
}

exports.expressUse = function (app, logger) {
    //页面请求日志,用auto的话,默认级别是WARN  
    //app.use(log4js.connectLogger(dateFileLog, {level:'auto', format:':method :url'}));  
    //app.use(log4js.connectLogger(logger, { level: 'info', format: ':method :url' }));
    log4js.connectLogger && log4js.connectLogger(logger, { level: 'auto' });
}

exports.requestLogMiddleware = function() {
    return Raven.requestHandler();
}

exports.init = init;

exports.initMicro = ({ appName, sentry }) => init({ appName, sentry });